/**
 * Created by Administrator on 2017/9/22.
 */
$(function(){


    /*顶部图片关闭按钮*/
    var oClose = document.getElementById('close');
    oClose.onclick =function(){
        oClose.parentNode.style.display="none";
    }
    //搜索框
    $(".text").on("focus",function(){
        $(this).val("");
    })
    $(".text").on("blur",function(){
        $(this).val("请输入商品名称,支持拼音搜索");
    })


    // all显示
    $(".all").on("mouseenter",function(){
        $(".menuBox .menuList").css("height",480);
        $(".menuBox .menuList").css("overflow","visible");
    })
    $(".all").on("mouseleave",function(){
        $(".menuBox .menuList").css("height",0);
        $(".menuBox .menuList").css("overflow","");
    })
    /*菜单栏显示*/
    /*进入时*/
    $(".menuBox .menuList>li").on("mouseenter",function(){
        $(".menuBox .menuList").css("overflow","visible")
        $(".menuBox .menuList").css("height",480);
        $(this).find("i").stop().animate({"margin-left":10},300).end().css("background","#a90000").children("p").children("a").css("color","#fff");
        $(".conBox").eq($(this).index()).css({"display":"block"}).stop().animate({paddingLeft:15,"opacity":0.98},300);

    });
    /*离开时*/
    $(".menuBox .menuList>li").on("mouseleave",function(){
        $(".menuBox .menuList").css("height",0);
        $(".menuBox .menuList").css("overflow","");
        $(this).find("i").stop().animate({"margin-left":0},300).end().css("background","#cb3e25").children("p").children("a").css("color","#eca598");
        $(".conBox").eq($(this).index()).css({"display":"none"}).stop().animate({paddingLeft:0,"opacity":0.5},300);
    });

    // 导航栏的指针
    //鼠标放上
    $(".nav-list>li").on("mouseenter",function(){
        var num=0;
        var inDex =$(this).index();
        var wid = $(this).find("a").width();
        $(".nav-list>li").eq(0).children("a").css("color","#666");
        //指到首页时
        if(inDex==0){
            $(".uline").animate({"left":0,"width":wid});
        }
        $(".nav-list>li").each(function(index,ele){
            num += ele.offsetWidth;
            if(index == inDex-1){
                $(".uline").stop().animate({"left":num,"width":wid},200);
            }
        })
    })
    // 鼠标拿开
    $(".nav-list").on("mouseleave",function(){
        $(".uline").animate({"left":0,"width":32});
        $(".nav-list>li").eq(0).children("a").css("color","#CB351A");
    })


    //整点抢
    $(".b1>i").eq(0).css("left",13)
    $(".b1>i").eq(1).css("left",33)
    $(".b1>i").eq(2).css("left",53)
    $(".b2>i").eq(0).css("left",13)
    $(".b2>i").eq(1).css("left",33)
    $(".b2>i").eq(2).css("left",53)
    var timer = setInterval(function(){
        $(".b1>i").eq(0).animate({"top":-36},700,function(){
            $(this).css("top",0);
        });
        $(".b1>i").eq(1).animate({"top":-36},800,function(){
            $(this).css("top",0);
        });
        $(".b1>i").eq(2).animate({"top":-36},900,function(){
            $(this).css("top",0);
        });
        $(".b2>i").eq(0).animate({"top":-36},700,function(){
            $(this).css("top",36)
        });
        $(".b2>i").eq(1).animate({"top":-36},800,function(){
            $(this).css("top",36)
        });
        $(".b2>i").eq(2).animate({"top":-36},900,function(){
            $(this).css("top",36)
        });
    },2000)


    //填数据
   // path=../json/today.json&index=0
    var str = window.location.href;
    var obj={};
    if(str.indexOf("?")!= -1){
        var arr = str.split("?");
        if(arr[1].indexOf("&")!=-1){
            var arr2 = arr[1].split("&");
            for(var i=0;i<arr2.length;i++){
                if(arr2[i].indexOf("=")!=-1){
                    var arr3 =arr2[i].split("=");
                    obj[arr3[0]]=arr3[1];
                }
            }
        }else{
            if(arr[1].indexOf("=")!=-1){
                var arr2 = arr[1].split("=");
                obj[arr2[0]]=arr2[1];
            }
        }
    }
    $.ajax({
        url:obj.path,
        success:function(res){
            if(obj.num){
                /*大图*/
                // console.log(1);
                $(".showGoods .jqzoom>img").prop("src",res.day[obj.num-1][obj.index].bigpic);
                /* 动态小图 */
                for(var i=0;i<res.day[obj.num-1][obj.index].smallpic.length;i++){
                    $(".spec-list>ul").append("<li><img src='"+res.day[obj.num-1][obj.index].smallpic[i]+"' alt=''></li>");
                }
                //商品名
                $(".goodsName span").text(res.day[obj.num-1][obj.index].name);
                //销售价
                $(".pirce .dd  span").text(res.day[obj.num-1][obj.index].pirce);
                //原价
                $(".opirce del").text(res.day[obj.num-1][obj.index].oprice);
                //销售量
                $(".ass").children("span").eq(0).children("em").text(res.day[obj.num-1][obj.index].sales);
                //评价
                $(".ass").children("span").eq(1).children("em").text(res.day[obj.num-1][obj.index].appraise);
                //赠豆
                $(".ass").children("span").eq(2).children("em").text(res.day[obj.num-1][obj.index].zeng);
                //属性
                $(".sumKid .dd span").text(res.day[obj.num-1][obj.index].guige);
                //库存
                $(".sumNum .dd>span>span").text(res.day[obj.num-1][obj.index].kucun);
                //人气
                $(".addBox a").text(res.day[obj.num-1][obj.index].renqi);
                //topTitle
                for(var i=0;i<res.day[obj.num-1][obj.index].topTitle.length-1;i++){
                    $(".topCon").append("<a href='main.html'>"+res.day[obj.num-1][obj.index].topTitle[i]+"</a>")
                }
                $(".topCon").append("<span>"+res.day[obj.num-1][obj.index].topTitle[res.day[obj.num-1][obj.index].topTitle.length-1]+"</span>");

            }else{
                /*大图*/
                $(".showGoods .jqzoom>img").prop("src",res.day[obj.index].bigpic);
                /* 动态小图 */
                for(var i=0;i<res.day[obj.index].smallpic.length;i++){
                    $(".spec-list>ul").append("<li><img src='"+res.day[obj.index].smallpic[i]+"' alt=''></li>");
                }
                //商品名
                $(".goodsName span").text(res.day[obj.index].name);
                //销售价
                $(".pirce .dd  span").text(res.day[obj.index].pirce);
                //原价
                $(".opirce del").text(res.day[obj.index].oprice);
                //销售量
                $(".ass").children("span").eq(0).children("em").text(res.day[obj.index].sales);
                //评价
                $(".ass").children("span").eq(1).children("em").text(res.day[obj.index].appraise);
                //赠豆
                $(".ass").children("span").eq(2).children("em").text(res.day[obj.index].zeng);
                //属性
                $(".sumKid .dd span").text(res.day[obj.index].guige);
                //库存
                $(".sumNum .dd>span>span").text(res.day[obj.index].kucun);
                //人气
                $(".addBox a").text(res.day[obj.index].renqi);
                //topTitle
                for(var i=0;i<res.day[obj.index].topTitle.length-1;i++){
                    $(".topCon").append("<a href='main.html'>"+res.day[obj.index].topTitle[i]+"</a>")
                }
                $(".topCon").append("<span>"+res.day[obj.index].topTitle[res.day[obj.index].topTitle.length-1]+"</span>");
            }




            //大图小图路径一致
            $(".bigImg").prop("src",$(".smallImg").prop("src"));

            //鼠标悬停选小图路径

            $(".spec-list ul li").on("mouseenter",function(){
                $(this).children("img").css({"border":"2px solid #ff6600","padding":"1"}).end().siblings().children("img").css({"border":"","padding":"2"});
                $(".smallImg").prop("src",$(this).children("img").prop("src"));
                //大图小图路径一致
                $(".bigImg").prop("src",$(".smallImg").prop("src"));
            })












            //购买数量加减
            var goodsCount =1;
            var goodsCountMax=$(".sumNum .dd>span>span").text();

            // console.log($(".sumNum .dd>span>span").text());
            $(".sumNum .left").on("click",function(){
                goodsCount--;
                if(goodsCount<1){
                    goodsCount=1;
                    $(".sumNum .left").css({"cursor":"not-allowed","color":"rgb(204, 204, 204)"});
                }
                if(goodsCount<goodsCountMax){
                    $(".sumNum .right").css({"cursor":"","color":""});
                }
                $(".sumNum input").val(goodsCount);
            })


            $(".sumNum .right").on("click",function(){
                goodsCount++;
                if(goodsCount>1){
                    $(".sumNum .left").css({"cursor":"","color":""});
                }
                if(goodsCount>goodsCountMax){
                    goodsCount=goodsCountMax;
                    $(".sumNum .right").css({"cursor":"not-allowed","color":"rgb(204, 204, 204)"});

                }
                $(".sumNum input").val(goodsCount);
            })


        }

    });


    //放大镜效果

    var _smallImg = $(".smallImg"); //小图
    var _bigImg = $(".bigImg"); //大图
    var _smallArea = $(".smallArea"); //小区域
    var _bigArea = $(".bigArea"); //大区域

    //放大系数/放大比例
    var scale = _bigImg.width() / _smallImg.width();


    //鼠标移动事件
    $("section").mousemove(function(e){

        var leftSide = _smallImg.offset().left; //小图左边界
        var rightSide = leftSide + _smallImg.width(); //右边界
        var topSide = _smallImg.offset().top; //上边界
        var bottomSide = topSide + _smallImg.height(); //下边界

        //如果在小图区域内
        if (e.pageX > leftSide && e.pageX < rightSide && e.pageY > topSide && e.pageY < bottomSide) {

            //显示小区域
            _smallArea.css("display", "block");
            _bigArea.css("display", "block");
            var x = e.pageX - _smallImg.offset().left - _smallArea.width()/2;
            var y = e.pageY - _smallImg.offset().top - _smallArea.height()/2;

            // console.log(_smallImg.offset().top);
            //
            // console.log(_smallImg.offset().left);
            //如果超出左边界, 则设置x为0
            if (x < 0) {
                x = 0;
            }
            //如果超出右边界, 则设置为右边界位置的值
            else if ( x > _smallImg.width()-_smallArea.width() ) {
                x = _smallImg.width()-_smallArea.width();
            }

            //如果超出上边界, 则最小为0
            if (y < 0) {
                y = 0;
            }
            //如果超出下边界, 则设置为下边界位置的值
            else if ( y > _smallImg.height()-_smallArea.height() ) {
                y = _smallImg.height()-_smallArea.height();
            }


            //移动小区域
            _smallArea.css({left: x, top: y});

            //移动大图的位置
            _bigImg.css({left: -x*scale, top:-y*scale});

        }
        else {
            //隐藏小区域
            _smallArea.css("display", "none");
            _bigArea.css("display", "none");
        }

    })


    //右边列表

    $(".cart-list ul").find(".kf").siblings().on("mouseenter",function(){
        $(this).find(".chu").stop().animate({"left":"-80","width":"80"});
    });
    $(".cart-list ul").find(".kf").on("mouseenter",function(){
        $(this).find(".kftc").stop().animate({"left":"-210","width":"210"})
    });
    $(".cart-list ul").find(".kf").siblings().on("mouseleave",function(){
        $(this).find(".chu").stop().animate({"left":"","width":""});
    });
    $(".cart-list ul").find(".kf").on("mouseleave",function(){
        $(this).find(".kftc").stop().animate({"left":"","width":""})
    });

    $(".cart-list ul").find(".erweima").on("mouseenter",function(){
        $(this).find(".chu").stop().animate({"left":"-240","width":"240"});
    });
    $(".cart-list ul").find(".kf").on("mouseleave",function(){
        $(this).find(".chu").stop().animate({"left":"","width":""})
    });

    // 购物车
    // 点击

    var gouNum=0;
    $(".cart").on("click",function(){
        gouNum++;
        if(gouNum%2!=0){
            $(".cart").children("a").eq(1).css("background","#ca3619");
            $(".rightBox").animate({"right":"0"});
        }else{
            $(".cart").children("a").eq(1).css("background","");
            $(".rightBox").animate({"right":"-280"});
        }

    });


    //回到顶部
    $(".back").on("click",function(){
        $("body").animate({"scrollTop":0});
    });




    //获取登录信息
    var str = $.cookie("user");
    if(str){
        $("#user").on("click",function(){
            window.location.href="shopping.html";
        });
        $("#action").on("click",function(){
            // window.location.href="login.html";
            $("#user").text("请登录");
            $("#action").text("免费注册");
            $.removeCookie("user");
            $.removeCookie("goods");
            window.history.go(0);
        });
        var objx = JSON.parse(str);
        $("#user").text(objx.uname);
        $("#action").text("退出");
    }else{
        $("#user").on("click",function(){
            window.location.href="login.html";
        });
        $("#action").on("click",function(){
            window.location.href="reg.html";
            $.removeCookie("user");
        });
    }



    //加入购物车信息提取
    $("#bt").on("click",function(){
        var goodsArr =[];
        var objGoods ={};
        var goodsStr = $.cookie("goods");
        // console.log(goodsStr);
        var goodsrc = $(".spec-list ul").find("li").eq(0).children("img").attr("src");
        if(goodsStr){
            var goodsObj = JSON.parse(goodsStr);

            objGoods ={"path":goodsrc,"sum":$("#sum").val(),"name":$(".goodsName span").text(),"price":$(".pirce .dd span").text()};

            //判断加入购物车的物品是否存在
            var goodsCount = goodsObj.length;
            var countxx = goodsObj.length;

            for(var i=0;i<countxx;i++){

                if(goodsObj[i].name == objGoods.name){

                    goodsObj[i].sum = parseInt(objGoods.sum) +parseInt(goodsObj[i].sum);
                    $.cookie("goods",JSON.stringify(goodsObj),{expires:7});
                    console.log($.cookie("goods"));

               }else{
                   goodsCount--;
                }
               if(goodsCount==0){

                   goodsArr=goodsObj;
                   goodsArr.push(objGoods);
                   $.cookie("goods",JSON.stringify(goodsArr),{expires:7});
                   console.log($.cookie("goods"));
               }
            }

        }
        else{
             objGoods =[{"path":goodsrc,"sum":$("#sum").val(),"name":$(".goodsName span").text(),"price":$(".pirce .dd span").text()}];
            $.cookie("goods",JSON.stringify(objGoods),{expires:7});
            console.log($.cookie("goods"));
        }



        //右侧购物车内容添加
        //如果没有cookie的内容
        if(!$(".newCon")){
            $(".nopublic").html("");
            var goodslist = $.cookie("goods");
            var listobj = JSON.parse(goodslist);
            for(var i = 0; i < listobj.length; i++){
                $(".nopublic").html("<div class='newCon'><img src='"+listobj[i].path+"' alt=''><a href='#'>"+listobj[i].name+"</a><p>价格："+listobj[i].price+"</p><div>数量："+listobj[i].sum+"</div></div>")

            }
        }else{
            //如果有
            var goodslist = $.cookie("goods");
            var listobj = JSON.parse(goodslist);
            $(".nopublic").html("");
            // console.log(listobj);
            // console.log(listobj.length);
            for(var i = 0; i < listobj.length; i++){

                $(".nopublic").append("<div class='newCon'><img src='"+listobj[i].path+"' alt=''><a href='#'>"+listobj[i].name+"</a><p>价格："+listobj[i].price+"</p><div>数量："+listobj[i].sum+"</div></div>")

            }

        }


        //购物车数量变化
        $(".cart-num").text($(".newCon").length);

    })


    //刷新时加载购物车内容
    var goodslist = $.cookie("goods");

    if(goodslist){
        $(".nopublic").html("");
        var listobj = JSON.parse(goodslist);

        for(var i = 0; i < listobj.length; i++){

            $(".nopublic").append("<div class='newCon'><img src='"+listobj[i].path+"' alt=''><a href='#'>"+listobj[i].name+"</a><p>价格："+listobj[i].price+"</p><div>数量："+listobj[i].sum+"</div></div>")

        }
    }

    //购物车数量变化
    $(".cart-num").text($(".newCon").length);


    //去购物车
    $(".goodsBtn a").on("click",function(){
        //判断如果登录了
       if($("#action").text()=="退出"){

           //先获取数据库中当前用户已有的信息
           var jsonObj = {"uname":$("#user").text()};
        $.ajax({
            url:"http://localhost/1706/myitem/select.php",
            type:"post",
            dataType:"json",
            data:jsonObj,
            success:function(res){
                console.log(res);
                console.log(res.data[0].goods);
                //如果数据库中有值
                if(res.data[0].goods&&res.data[0].goods!="null"){
                    //如果cookie中有值
                   if($.cookie("goods")){
                       var Goods = JSON.parse(res.data[0].goods);
                       console.log("数据库");
                       console.log(Goods);

                       //上传cookie数据到数据库
                       var goodslist = $.cookie("goods");
                       console.log(goodslist);
                       var listobj = JSON.parse(goodslist);


                       for(var i=0;i<listobj.length;i++){
                           console.log(listobj[i].name);
                           listobj[i].name =  encodeURIComponent(listobj[i].name);
                       }


                       console.log(listobj);

                       //便利
                       // for(var j=0;j<listobj1.length;j++){
                       //      var count11 =0;
                       //     for(var i=0;i<Goods.length;i++){
                       //
                       //         if(listobj1[j].path == Goods[i].path){
                       //             console.log(2);
                       //             // console.log(Goods[i]);
                       //             // console.log(Goods[i].sum);
                       //             // console.log(listobj[j].sum);
                       //             Goods[i].sum = Number(Goods[i].sum)+Number(listobj1[j].sum);
                       //             break;
                       //         }
                       //         else{
                       //             count11++;
                       //             console.log(count11);
                       //             if(count11 == Goods.length){
                       //                 console.log(1);
                       //                 Goods.push(listobj1[j]);
                       //             }
                       //         }
                       //     }
                       // }

                       listobj.forEach(function(eleck,indexck){
                           //ele--{serial: "dis02", sum: "6"}
                           var tpr = 0;
                           Goods.forEach(function(ele,index){
                               if(ele.path==eleck.path){
                                   //cookie中的该商品用户已经加入了自己的购物车，就让件数相加
                                   ele.sum=parseInt(ele.sum)+parseInt(eleck.sum);
                                   return;
                               }

                               tpr++;
                               console.log(tpr);
                               if(tpr==Goods.length){
                                   //cookie中该商品用户还没有存入自己的购物车，就将该商品的的信息和件数push进用户的购物车数组
                                   Goods.push(eleck);
                               }

                           })
                       });



                       var datax = {"uname":$("#user").text(),"goods":Goods};
                       console.log(datax);


                       $.ajax({
                           url:"http://localhost/1706/myitem/change.php",
                           data:datax,
                           type:"post",
                           dataType:"json",
                           success:function(res){

                               $.removeCookie("goods");
                               window.location.href = "shopping.html";

                           }
                       });
                   }
                   else{
                       window.location.href = "shopping.html";
                   }
               }
               else{
                    //数据库中没有值
                    if($.cookie("goods")){
                        //如果cookie有值
                        var goodslist = $.cookie("goods");

                        var listobj = JSON.parse(goodslist);

                        for(var i=0;i<listobj.length;i++){
                            console.log(listobj[i].name);
                            listobj[i].name =  encodeURIComponent(listobj[i].name);
                        }

                        var datax = {"uname":$("#user").text(),"goods":listobj};
                        console.log(datax);
                        $.ajax({
                            url:"http://localhost/1706/myitem/change.php",
                            data:datax,
                            type:"post",
                            dataType:"json",
                            success:function(res){
                                $.removeCookie("goods");
                                window.location.href = "shopping.html";

                            }
                        });
                    }
                    else{
                        window.location.href = "shopping.html";
                    }

               }


            }
        })

       }
       else{
           window.location.href = "login.html";
       }
    })


})